/**
 * 目标：实现art-template模板引擎
 */
const Koa = require('koa')
const app = new Koa()
const path = require('path')

const template = require('art-template')
const render = require('koa-art-template')
render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
})

app.use(async (ctx, next) => {

  await ctx.render('index', {
    title: 'hello koa-art-template',
    list: ['张三', '李四', '王五', '赵六'],
    obj: {
      name: '熊大',
      bro: '熊二'
    },
    a: 10,
    b: 20,
    html: `<h2 style='color:red;'>原文输出红色样式</h2>`,
    flag: false,
    date: Date.now()
  })
})

/**
 * 注册过滤器 
 * 注意：需要先引入art-template
 * @param {timeStr} dateTime 
 * @returns 
 */
template.defaults.imports.getDate = (dateTime) =>{
  const datetime = new Date(dateTime)

  const year = datetime.getFullYear()
  const month = ("0" + (datetime.getMonth() + 1)).slice(-2)
  const date = ("0" + datetime.getDate()).slice(-2)
  const hour = ("0" + datetime.getHours()).slice(-2)
  const minute = ("0" + datetime.getMinutes()).slice(-2)
  const second = ("0" + datetime.getSeconds()).slice(-2)

  return `${year}-${month}-${date} ${hour}:${minute}:${second}`
}
// 模板变量
template.defaults.imports.log = console.log;
// 开启压缩页面
template.defaults.minimize = true

app.listen(3000, () => {
  console.log('服务器在127.0.0.1:3000运行中...')
})